package com.summerbird.mallchat.common.common.event.listener;

import com.summerbird.mallchat.common.chat.dao.MessageDao;
import com.summerbird.mallchat.common.chat.domain.entity.Message;
import com.summerbird.mallchat.common.chat.domain.entity.Room;
import com.summerbird.mallchat.common.chat.service.cache.RoomCache;
import com.summerbird.mallchat.common.common.constant.MQConstant;
import com.summerbird.mallchat.common.common.domain.dto.MsgSendMessageDTO;
import com.summerbird.mallchat.common.common.event.MessageSendEvent;
import com.summerbird.mallchat.transaction.service.MQProducer;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.validation.constraints.NotNull;

@Slf4j
@Component
public class MessageSendListener {

    @Autowired
    private MQProducer mqProducer;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private RoomCache roomCache;

    @SneakyThrows
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = MessageSendEvent.class, fallbackExecution = true)
    public void messageRoute(MessageSendEvent event){
        Long msgId = event.getMsgId();
        mqProducer.sendSecureMsg(MQConstant.SEND_MSG_TOPIC, new MsgSendMessageDTO(msgId), msgId);
    }


    public void handlerMsg(@NotNull MessageSendEvent event){
        Message message = messageDao.getById(event.getMsgId());
        Room room = roomCache.get(message.getRoomId());
        if(room.isHotRoom()){
            // TODO:AI机器人回复
            //openAIService.chat(message);
        }
    }

}
